package com.mylib.libcore.utils;

import android.content.Intent;
import android.util.Log;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.JsonObject;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.customapi.CustomServiceApi;
import com.mylib.libcore.network.rx.RxResultHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.PublishSubject;

import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;

/**
 * 检测toekn
 * @author Administrater
 * @time 2019-12-28 14:23
 */
public class TokenUtil {
    private AtomicBoolean mRefreshing = new AtomicBoolean(false);
    private PublishSubject<Object> mPublishSubject;
    private static CustomServiceApi customServiceApi;
    public static TokenUtil getInstance() {
        customServiceApi = RetrofitUtil.getAppRetrofit().create(CustomServiceApi.class);
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final TokenUtil INSTANCE = new TokenUtil();
    }

    private TokenUtil() {

    }

    public Observable<Object> getNetTokenLocked() {
        Log.d("token_error","重新获取token");
//        if (mRefreshing.compareAndSet(false, true)) {
//            getNewToken();
//        }
        getNewToken(true);
        if(mPublishSubject == null) {
            mPublishSubject = PublishSubject.create();
        }

        return mPublishSubject;
    }

    public Observable<Object> getMineNetTokenLocked() {
        Log.d("token_error","重新获取getMineNetTokenLockedtoken");
//        if (mRefreshing.compareAndSet(false, true)) {
//            getNewToken();
//        }
        getNewToken(false);
        if(mPublishSubject == null) {
            mPublishSubject = PublishSubject.create();
        }

        return mPublishSubject;
    }

    public void getNewToken(boolean isToLogin) {
        JsonObject jsonObject = new JsonObject();
            HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("ctl", "QSUser");
        hashMap.put("met", "refreshToken");
        hashMap.put("uToken", AppContext.getInstance().getAppPreferencesHelper().getKeyValue("uToken"));
        hashMap.put("rToken", AppContext.getInstance().getAppPreferencesHelper().getKeyValue("rToken"));
        hashMap.put("typ", "json");
        RxResultHelper.getHttpObservableNone(AppContext.getInstance().getContext(), customServiceApi.getNewToken(hashMap,jsonObject))
                .subscribe(new Observer<BaseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseBean bean) {
                        Log.d("token_refresh",JsonUtil.toJson(bean.getData()));
                        cancelTokenRefresh();
                        if(!UIUtils.isEmpty(bean)){
                            if(bean.getCode() == BASE_SUCCESS_CODE){
                                try {

                                    Log.d("token_error",JsonUtil.toJson(bean.getData()));
                                    JSONObject jsonData = new JSONObject(JsonUtil.toJson(bean.getData()));
                                    String uToken = jsonData.optString("uToken");
                                    String rToken = jsonData.optString("rToken");
                                    String nToken = jsonData.optString("nToken");
                                    if(!UIUtils.isEmpty(uToken)){
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("uToken",uToken);
                                    }
                                    if(!UIUtils.isEmpty(rToken)){
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("rToken",rToken);
                                    }
                                    if(!UIUtils.isEmpty(nToken)){
                                        AppContext.getInstance().getAppPreferencesHelper().setKeyValue("nToken",nToken);
                                    }
                                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("isLogin","1");
                                } catch (JSONException e) {

                                    e.printStackTrace();
                                }
                            }else {
                                if(isToLogin){

                                    if(!UIUtils.isEmpty(bean.getMsg())){
                                        ToastUtil.show(bean.getMsg());
                                    }
                                }else {
                                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("isLogin","0");
                                }

                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("token_error","250");
                        if(isToLogin){

                            if(!UIUtils.isEmpty(e.getMessage())){
                                ToastUtil.show(e.getMessage());
                            }
                        }else {
                            AppContext.getInstance().getAppPreferencesHelper().setKeyValue("isLogin","0");
                        }

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void cancelTokenRefresh() {
        if (mPublishSubject != null)
            mPublishSubject.onComplete();
        mPublishSubject = null;
        if(!UIUtils.isEmpty(mRefreshing)){
            mRefreshing.set(false);
        }

    }



}
